from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse,HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import F
from django.urls import reverse
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User,Group
from django.contrib.auth import login, logout, authenticate
from django.views.decorators.cache import cache_page
from rest_framework_extensions.cache.decorators import cache_response
from .forms import *  # 如果你有自定义的登录表单，否则可以直接使用AuthenticationForm
from .models import MyUser
import json




def delete(request, id):
    obj = MyUser.objects.get(id=id)
    obj.delete()
    json_dict = {}
    json_dict["code"] = 200
    json_dict["msg"] = "删除数据成功"
    return JsonResponse(json_dict)


@permission_required("apps.user.view_myuser")
def index(request):
    if request.method == "GET":
        level = request.GET.get("level")
        truename = request.GET.get("truename", '')
        status = request.GET.get("status")

        search_dict = {
            key: value for key, value in (("level", level), ("truename", truename), ("status", status)) if value
        }

        datas = MyUser.objects.filter(**search_dict).order_by("-id")

        page_size = 8
        try:
            curr_page = int(request.GET.get("page", 1))
        except ValueError:
            curr_page = 1

        paginator = Paginator(datas, page_size)

        try:
            users = paginator.page(curr_page)
        except PageNotAnInteger:
            users = paginator.page(1)
        except EmptyPage:
            # 如果请求的页码超出范围，则显示最后一页
            users = paginator.page(paginator.num_pages)

        context = {
            'level': level,
            'truename': truename,
            'status': status,
            'users': users,
        }
        print(context)
        return render(request, 'back/users/index.html', context=context)
    else:
        # 处理非GET请求（如果需要）
        return HttpResponse("Only GET requests are allowed.", status=405)




def ajax_member(request):
    total = MyUser.objects.count()
    users = MyUser.objects.order_by("-id")
    rows = []
    datas = {"total": total, "rows": rows}
    for user in users:
        rows.append({
            "id": user.id,
            "username": user.username,
            "truename": user.truename,
            "sex": user.sex,
            "email": user.email,
        })
    return JsonResponse(datas, safe=False, json_dumps_params={'ensure_ascii': False, "indent": 4})



def user_reg(request):
    if request.method == "GET":
        form_obj = UserRegForm()
        return render(request, 'video/users/user_reg.html', {"form_obj": form_obj})
    if request.method == "POST":
        form_obj = UserRegForm(request.POST, request.FILES)
        if form_obj.is_valid():
            uname = request.POST.get("username", '')
            users = MyUser.objects.filter(username=uname)
            if users:
                for user in users:
                    user_img = user.user_img
                info = '用户已经存在'
            else:
                form_obj.cleaned_data.pop("re_password")
                form_obj.cleaned_data["is_staff"] = 0
                form_obj.cleaned_data["is_superuser"] = 0  # 非管理员
                # 接收页面传递过来的参数，进行用户新增


                user = MyUser.objects.create_user(**form_obj.cleaned_data)
                user_img = user.user_img

                info = '注册成功,请登陆'
            return render(request, 'video/users/user_reg.html', {"form_obj": form_obj, "info": info, "user_img": user_img})
        else:
            errors = form_obj.errors
            print(errors)
            return render(request, "video/users/user_reg.html", {'form_obj': form_obj, 'errors': errors})
        # return render(request,'video/user_reg.html',{"form_obj":form_obj})


def user_out(request):
    if request.user.is_authenticated:
        logout(request)
        return redirect(reverse(''))
    else:
        return redirect(reverse(''))


def user_login(request):
    if request.method == "POST":
        # 假设你使用Django的AuthenticationForm，或者你自己的表单
        # 这里以Django的AuthenticationForm为例

        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            # 表单验证通过，尝试登录
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None and user.is_active:
                # 用户存在且激活，登录
                login(request, user)
                # 登录成功后重定向到某个页面，例如首页
                return HttpResponseRedirect(reverse(''))
            else:
                # 用户名或密码错误
                return render(request, 'video/users/user_login.html', {'error': 'Invalid username or password.'})
        else:
            # 表单验证失败
            return render(request, 'video/users/user_login.html', {'form': form})
    elif request.user.is_authenticated:
        # 用户已经登录，重定向到首页或其他页面
        return redirect(reverse(''))
    else:
        # 初始化表单
        form = AuthenticationForm()
    return render(request, 'video/users/user_login.html', {'form': form})


def ajax_login_data(request):
    if request.method == "GET":
        if request.user.is_authenticated:
            return redirect('index')
        else:
            return render(request, "video/users/user_login.html")

    if request.method=="POST":
        uname = request.POST.get("username", '')
        pwd = request.POST.get("password", '')
        json_dict = {}
        if uname and pwd:  ## 不为空的情况下，查询数据库
            if MyUser.objects.filter(username=uname):  # 判断用户是否存在
                # 如果存在，进行验证
                user = authenticate(username=uname, password=pwd)
                if user:  # 如果验证通过
                    if user.is_active:  # 如果用户状态为激活
                        login(request, user)  # 进行登陆操作，完成session的设置
                        json_dict["code"] = 1000
                        json_dict["msg"] = "登陆成功"
                    else:
                        json_dict["code"] = 1001
                        json_dict["msg"] = "用户还未激活"
                else:
                    json_dict["code"] = 1002
                    json_dict["msg"] = "账号密码不对，请重新输入"
            else:
                json_dict["code"] = 1003
                json_dict["msg"] = "用户账号有误，请查询"
        else:
            json_dict["code"] = 1004
            json_dict["msg"] = "用户名或者密码为空"
        return JsonResponse(json_dict)


def diy_loginView(request):
    if request.method == "GET":
        return render(request, '6/login.html')
    if request.method == "POST":
        uname = request.POST.get("username", '')
        pwd = request.POST.get("password", '')
        if MyUser.objects.filter(username=uname):  # 判断用户是否存在
            # 如果存在，进行验证
            user = authenticate(username=uname, password=pwd)
            if user:  # 如果验证通过
                if user.is_active:  # 如果用户状态为激活
                    login(request, user)  # 进行登陆操作，完成session的设置
                    info = "登陆成功"
                    return redirect('/userbaseinfo_add')
                    # next=request.GET.get("next")
                    # if next:
                    #    print("http://"+request.get_host()+next)
                    #    return HttpResponseRedirect("http://"+request.get_host()+next)
                else:
                    info = "用户还未激活"
            else:
                info = "账号密码不对，请重新输入"
        else:
            info = '用户账号不存在，请查询'
        return render(request, '6/login.html', {"info": info})

